#! /bin/zsh  # Not needed but makes syntax highlighting easier

# source'd from /etc/profile.d/segfault.sh

# CY="\e[1;33m" # yellow
# CR="\e[1;31m" # red
# CC="\e[1;36m" # cyan
# CG="\e[1;32m" # green
# CDC="\e[0;36m" # cyan
# CDR="\e[0;31m" # red
# CN="\e[0m"    # none
# CW="\e[1;37m" # white
# CF="\e[2m"    # faint

# ZSH specific
function cnf_preexec() {
    local cmd

    cmd="$1"
    # Remove any variable like in `FOO=blah duf`
    # Test: X="FOO BAR" Y="hello world" Z=mememe whoami
    while :; do
        cmd="${cmd#"${cmd%%[^[:space:]]*}"}" # remove leading whitespace characters
        [[ $cmd != *" "* ]] && break
        # Check if first string before \s is a variable (contains '=')
        [[ ${cmd%% *} != *"="* ]] && break

        # HERE: It's a variable. X=foo, X="foo" or X="foo bar". Remove it for 'cmd'
        [[ ${cmd%% *} != *"=\""* ]] && {
            # HERE: variable without quotes
            cmd=${cmd#* }
            continue;
        }
        # HERE: X="foo" or X="foo bar"
        cmd=${cmd#*=\"}
        cmd=${cmd#*\" }
    done
    typeset -g cnf_command="${cmd%% *}"

    whence -- "${cnf_command}" >& /dev/null && return
    # HERE: command not found
    [ -n "$cnf_once" ] && return
    typeset -g cnf_once="1"
    echo -en "💥 \e[0;31m"
}

function cnf_precmd() {
    cnf_ret=$?

    unset cnf_once
    echo -en "\e[0m"
    (($cnf_ret)) && [ -n "$cnf_command" ] && {
        whence -- "${cnf_command}" >& /dev/null ||
            echo -e "\e[0;34m[\e[0;33mSF\e[0;34m]\e[0m ¯\_(⊙︿⊙)_/¯ Like us to install \e[0;36m${cnf_command}\e[0m?\n\e[0;34m[\e[0;33mSF\e[0;34m] \e[1;37mTell us at https://t.me/thcorg\e[0m 🌈😘"
        unset cnf_command
    }
}

typeset -ga preexec_functions
typeset -ga precmd_functions
preexec_functions+=cnf_preexec
precmd_functions+=cnf_precmd
